package com.itliang.web.service;


import com.itliang.constant.RedisConstants;
import com.itliang.core.model.entity.system.SysUser;
import com.itliang.core.redis.RedisCache;
import com.itliang.core.result.CodeEnum;
import com.itliang.exception.BusinessException;
import com.itliang.security.custom.CustomUser;
import com.itliang.service.system.SysMenuService;
import com.itliang.service.system.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.itliang.constant.RedisConstants.OPERATION_PERMISSION_TTL;


@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Resource
    private SysMenuService sysMenuService;

    @Resource
    private RedisCache redisCache;

    @Override
    public UserDetails loadUserByUsername(String userAccount) {
        SysUser sysUser = sysUserService.getByUserAccount(userAccount);
        if (sysUser == null) {
            throw new BusinessException(CodeEnum.ACCOUNT_NOT_EXIST);
        }
        if (sysUser.getStatus() == 0) {
            throw new BusinessException(CodeEnum.ACCOUNT_STOP);
        }

        // 获取权限信息
        List<String> userButtonList = sysMenuService.getUserButtonList(sysUser.getId());
        // 转换security要求格式数据
        List<SimpleGrantedAuthority> permissionList = userButtonList.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        // 保存到redis
        String permissionKey = RedisConstants.OPERATION_PERMISSION_KEY + userAccount;
        redisCache.setCacheObject(permissionKey, permissionList, OPERATION_PERMISSION_TTL, TimeUnit.SECONDS);

        return new CustomUser(sysUser, permissionList);
    }
}
